import Vue from 'vue';
import VueRouter from 'vue-router';
import store from '../store';

const Home = () => import('../components/Home.vue');
const ConversationItem = () => import('../components/conversation/ConversationItem.vue');
const AVChatRoomItem = () => import('../components/trtc/AVChatRoomItem.vue');
const GroupVideoCallItem = () => import('../components/trtc/GroupVideoCallItem.vue');
const Waterfall = () => import('../components/utils/Waterfall.vue');
const Eclipse = () => import('../components/mycss/Eclipse.vue');
const CssButton = () => import('../components/mycss/CssButton.vue');
const ToDoList = () => import('../components/todolist/ToDoList.vue');

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    redirect: './home'
  },
  {
    path: '/home',
    name: 'home',
    component: Home
  },
  {
    path: '/conversation-item',
    name: 'conversation-item',
    component: ConversationItem
  },
  {
    path: '/avchatroom-item',
    name: 'avchatroom-item',
    component: AVChatRoomItem
  },
  {
    path: '/group-videocall-item',
    name: 'group-videocall-item',
    component: GroupVideoCallItem
  },
  {
    path: '/waterfall',
    name: 'waterfall',
    component: Waterfall
  },
  {
    path: '/eclipse',
    name: 'eclipse',
    component: Eclipse
  },
  {
    path: '/css-button',
    name: 'css-button',
    component: CssButton
  },
  {
    path: '/todo-list',
    name: 'todo-list',
    component: ToDoList
  }
];

const router = new VueRouter({
  mode: 'history',
  base: getAbsolutePath(),
  routes
});

// 增加路由守卫，避免用户刷新后还在需要登录的页面，影响用户体验
router.beforeEach((to, from, next)=>{
  if(!store.state.user.isLogin && (to.path === '/todo-list' || to.path === '/conversation-item' || to.path === '/group-videocall-item')){
    next({ path: '/home' });
  } else {
    next();
  }
});

function getAbsolutePath () {
  let path = location.pathname;
  return path.substring(0, path.lastIndexOf('/') + 1);
}

// 解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err);
}
export default router;
